//
//  UIImage+ZCHelp.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/6/1.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "UIImage+ZCHelp.h"

@implementation UIImage (ZCHelp)
//将UIImage转换为NSData
-(NSData *)imageToData{
    NSData *data;
    data = UIImageJPEGRepresentation(self,1.0);
    return data;
}

/**
 压缩图片 - 500kb以下
 
 @return Data - 图片data
 */
-(NSData *)scaleWithFileBytes:(NSInteger )fileBytes
{
    if (!self) {
        return nil;
    }
    if (fileBytes == 0) {
        fileBytes = 200;
    }
    CGFloat maxFileSize = fileBytes*1024;//500k以内
    CGFloat compression = 1;
    NSData *compressedData = UIImageJPEGRepresentation(self, compression);
    if ([compressedData length] > maxFileSize) {
        CGFloat offSet = maxFileSize/[compressedData length];
        compression = offSet;
        compressedData = UIImageJPEGRepresentation(self, compression);
        UIImage * imageNew = [UIImage imageWithData:compressedData];
        compressedData = UIImageJPEGRepresentation([self compressImage:imageNew newWidth:imageNew.size.width*compression], 1);
    }
    return compressedData;
}

/**
 等比缩放本图片大小

 @param image 原图
 @param newImageWidth 新宽度
 @return 新图
 */
-(UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, [UIScreen mainScreen].scale);
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

/**
 *scrollView截取的视图，tableView亦可，
 *saveToAlbum是否保存图片至相册，
 *block进度，progress=0为开始，progress=1为结束，可绘制loading图，文字提示等。
 */
+ (UIImage *)snapshotScreenIn:(UIScrollView *)scrollView andSaveToAlbum:(BOOL)saveToAlbum andProgressing:(void(^)(CGFloat progress))block
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        if (block) {
            block(0.5);//结束
        }
        return [[UIImage alloc] init];
    }
    if (@available(iOS 14, *)) {
        if (status == PHAuthorizationStatusLimited) {
            if (block) {
                block(0.5);//结束
            }
            return [[UIImage alloc] init];
        }
    }
    if (block) {
        block(0);//开始
    }
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
        UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, [UIScreen mainScreen].scale);
        
    } else {
        UIGraphicsBeginImageContext(scrollView.contentSize);
    }
    //先保存原来frame 和 偏移量
    CGPoint savedContentOffset = scrollView.contentOffset;
    CGRect savedFrame = scrollView.frame;
    CGSize contentSize = scrollView.contentSize;
    CGRect oldBounds = scrollView.layer.bounds;
    
    if(@available(iOS 13, *)){
        //iOS 13 系统截屏需要改变tableview 的bounds
        [scrollView.layer setBounds:CGRectMake(oldBounds.origin.x, oldBounds.origin.y, contentSize.width, contentSize.height)];
    }
    
    //偏移量归零
    scrollView.contentOffset = CGPointZero;
    //frame变为contentSize
    scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
    //截图
    [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    if(@available(iOS 13,*)){
        [scrollView.layer setBounds:oldBounds];
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //还原frame 和 偏移量
    scrollView.contentOffset = savedContentOffset;
    scrollView.frame = savedFrame;
    
    if (saveToAlbum) {
        if (status == PHAuthorizationStatusNotDetermined) {// 如果没决定, 弹出指示框, 让用户选择
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
                        if (block) {
                            block(1);//结束
                        }
                    });
                }else {
                    if (block) {
                        block(0.5);//结束
                    }
                }
            }];
        }else {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            if (block) {
                block(1);//结束
            }
        }
    }
    return image;
}







@end
